import { app } from "../../scripts/app.js";

// 基础 Widget 类
class BaseWidget {
    constructor() {
        this.value = null;
        this.element = null;
        this.node = null;
        this.name = null;
        this.type = "WIDGET";
        console.log(`[BaseWidget] 创建基础小部件`);
    }

    init(node, name, inputData) {
        console.log(`[BaseWidget] 初始化:`, { node: node?.type, name, inputData });
        
        this.node = node;
        this.name = name;
        this.value = inputData?.default || inputData?.options?.[0] || null;
        this.element = this.createElement();
        
        console.log(`[BaseWidget] 初始化完成:`, {
            name: this.name,
            value: this.value,
            element: this.element?.tagName
        });
        
        return this;
    }

    createElement() {
        throw new Error("Must be implemented by subclass");
    }

    getValue() {
        return this.value;
    }

    setValue(value, triggerChange = true) {
        if (this.value !== value) {
            this.value = value;
            if (triggerChange && this.node) {
                this.node.onWidgetChanged?.(this.name, this.value);
            }
        }
    }

    serialize() {
        return this.value;
    }
}

// 测试自定义 Widget
class TestCustomWidget extends BaseWidget {
    constructor() {
        super();
        this.type = "test_custom";
    }

    createElement() {
        console.log(`[TestCustomWidget] 创建元素`);
        
        const container = document.createElement("div");
        container.style.width = "100%";
        container.style.padding = "8px";
        container.style.backgroundColor = "var(--comfy-input-bg)";
        container.style.border = "2px solid var(--border-color)";
        container.style.borderRadius = "8px";
        container.style.margin = "4px 0";
        
        // 创建标题
        const title = document.createElement("div");
        title.style.fontSize = "12px";
        title.style.color = "var(--input-text)";
        title.style.marginBottom = "4px";
        title.textContent = "测试自定义 Widget";
        
        // 创建内容
        const content = document.createElement("div");
        content.style.fontSize = "10px";
        content.style.color = "var(--input-text)";
        content.textContent = `当前值: ${this.value || '未设置'}`;
        
        // 创建按钮
        const button = document.createElement("button");
        button.textContent = "点击测试";
        button.style.width = "100%";
        button.style.padding = "4px 8px";
        button.style.marginTop = "4px";
        button.style.backgroundColor = "var(--comfy-input-bg)";
        button.style.color = "var(--input-text)";
        button.style.border = "1px solid var(--border-color)";
        button.style.borderRadius = "4px";
        button.style.cursor = "pointer";
        
        button.addEventListener("click", () => {
            const newValue = Math.floor(Math.random() * 100);
            this.setValue(newValue);
            content.textContent = `当前值: ${newValue}`;
            console.log(`[TestCustomWidget] 按钮点击，新值: ${newValue}`);
        });
        
        container.appendChild(title);
        container.appendChild(content);
        container.appendChild(button);
        
        this.content = content;
        
        return container;
    }

    setValue(value, triggerChange = true) {
        super.setValue(value, triggerChange);
        
        if (this.content) {
            this.content.textContent = `当前值: ${value}`;
        }
    }
}

// 注册扩展
app.registerExtension({
    name: "test.addCustomWidget",
    
    async beforeRegisterNodeDef(nodeType, nodeData, app) {
        console.log(`[Extension] 注册节点: ${nodeData.name}`);
        
        // 注册自定义 Widget 类型
        const widgetTypes = {
            TestCustomWidget: TestCustomWidget
        };

        // 添加自定义 Widget 工厂函数
        nodeType.prototype.addCustomWidget = function(name, widgetType, options) {
            console.log(`[Node] 添加自定义小部件:`, {
                name,
                type: widgetType,
                options
            });
            
            if (!widgetTypes[widgetType]) {
                console.error(`未知的自定义小部件类型: ${widgetType}`);
                return null;
            }
            
            const widget = new widgetTypes[widgetType]();
            widget.init(this, name, options);
            
            if (!this.widgets) {
                this.widgets = [];
            }
            this.widgets.push(widget);
            
            console.log(`[Node] 自定义小部件添加成功:`, widget);
            return widget;
        };

        // 扩展节点创建方法
        const originalOnNodeCreated = nodeType.prototype.onNodeCreated;
        nodeType.prototype.onNodeCreated = function() {
            console.log(`[Node] 节点创建: ${this.type}`);
            
            if (originalOnNodeCreated) {
                originalOnNodeCreated.apply(this);
            }

            // 为所有节点添加测试自定义 Widget
            try {
                const testWidget = this.addCustomWidget("test_widget", "TestCustomWidget", {
                    default: 42,
                    description: "这是一个测试自定义 Widget"
                });
                
                if (testWidget) {
                    console.log(`[Node] 测试自定义 Widget 添加成功`);
                } else {
                    console.error(`[Node] 测试自定义 Widget 添加失败`);
                }
            } catch (error) {
                console.error(`[Node] 添加测试自定义 Widget 时出错:`, error);
            }
        };
    },

    async nodeCreated(node) {
        console.log(`[Extension] 节点创建事件: ${node.type}`);
        
        // 检查节点是否有 addCustomWidget 方法
        if (typeof node.addCustomWidget === 'function') {
            console.log(`[Extension] 节点支持 addCustomWidget 方法`);
            
            // 尝试直接调用 addCustomWidget
            try {
                const testWidget = node.addCustomWidget("direct_test", "TestCustomWidget", {
                    default: 100,
                    description: "直接调用测试"
                });
                
                if (testWidget) {
                    console.log(`[Extension] 直接调用 addCustomWidget 成功`);
                }
            } catch (error) {
                console.error(`[Extension] 直接调用 addCustomWidget 失败:`, error);
            }
        } else {
            console.log(`[Extension] 节点不支持 addCustomWidget 方法`);
        }
    }
});